package com.diancan.modules.admin.admin.QRCode;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.fastjson2.util.IOUtils;
import com.diancan.common.Result;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.FileOutputStream;

@RestController
@RequestMapping("qrcode")
@CrossOrigin
public class QrcodeController {
    @Value("${file.location}")
    String filelocation;
    @Value("${file.path}")
    String filepath;
    @Value("${file.domainName}")
    String domainName;
    private final QrConfig qrConfig;

    public QrcodeController(QrConfig qrConfig) {
        this.qrConfig = qrConfig;
    }

    /**
     * 二维码数据获取接口
     *
     * @param id 桌号
     * @return
     */
    @GetMapping("get")
    @SneakyThrows
    public Result getByQRCode(Integer id) {
        if (id == null) {
            return Result.buildFailureResult("桌号不能为空");
        }
        QrCodeUtil.generate(String.valueOf(id), qrConfig, "jpg", new FileOutputStream(filelocation + "qrcode/" + id + ".jpg"));
        return Result.buildSuccessResult(domainName + "qrcode/" + id + ".jpg");
    }

    @GetMapping("download")
    @SneakyThrows
    public byte[] download(Integer id) {
        QrCodeUtil.generate(String.valueOf(id), qrConfig, "jpg", new FileOutputStream(filelocation + "qrcode/" + id + ".jpg"));
        FileInputStream inputStream = new FileInputStream(filelocation + "qrcode/" + id + ".jpg");
        return inputStream.readAllBytes();
    }
}
